<?php

namespace app\admin\logic;
use app\admin\logic\BasicLogic;
use app\common\library\Upload;
use app\common\service\UploadService;
use app\common\service\CommonSystemImportService;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use app\admin\model\SmsRecordModel;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use app\common\library\RedissLock;
class TestLogic extends BasicLogic
{

    public $uploadName = 'common_test_upload_info';
    /**
     * @desc mq消息测试
     * @author xx
     * @date 2024-03-13
     */
    public function mqTest(){
        self::test_produce();
        return $this->jsonMessage(200, true, '操作成功', null);
    }


    /**
     * @desc mq测试生产方法
     * @author xx
     * @date 2024-03-13
     */
    public function test_produce(){
        $send_values = [
            'tel'=>'13879645980',
            'code'=>'456897',
            'message'=>'OK',
            'sms_type'=>1,
            'created_time'=>'2024-02-29 20:59:41',
            'expire_time'=>'2024-02-29 20:59:41',
        ];
        self::push_exception_link_sku_mq($send_values);
    }




    /**
     * mq测试推送方法
     * @author xx
     * @date 2024-03-13
     */
    public function push_exception_link_sku_mq($info=[]){
        set_time_limit(0);
        $res = MqTaskPushLogic::mq_task_push('', MqQueueName::QUEUE_FOLLOW_EXCEPTION_LINK_QUEUE, $info, false);
        if(!$res){
            return $this->jsonMessage(201, false, $res, null);
        }else{
            return $this->jsonMessage(200, true, '操作成功', null);
        }

    }




    /**
     * @return bool
     * @title  mq测试消费方法
     * @author luckyXiong
     * @Date   2024/03/13 10:55
     */
    public function follow_exception_link_consumer($params){
        set_time_limit(0);
        try{
            $push_arr = [
                'tel'         =>$params['tel'],
                'sms_type'    =>$params['sms_type'],
                'code'        =>$params['code'],
                'message'     =>$params['message'],
                'created_time'=>date("Y-m-d H:i:s", time()),
                'expire_time' =>date("Y-m-d H:i:s", time())
            ];
            //数据入库处理;
            (new smsRecordModel())->insert($push_arr);
            return true;
        }catch (\Exception $e){
            return $this->jsonMessage(201, false,$e->getMessage(), null);
        }
        return $this->jsonMessage(200, true, '操作成功', null);
    }



    /**
     * @desc 本地数据上传OSS
     * @author luckyXiong
     * @Date   2024/03/18 10:55
     */
    public function uploadTest($param=[]){

        $doc_url   = $param['url'];
        $order_id  = $param['order_id'];
        //地址上传到阿里云OSS;
        $service   = new UploadService();
        $BASE_PATH = dirname(__DIR__, 1);
        $local_dir = $BASE_PATH . '/runtime/package/';
        if (!is_dir($local_dir)) {
            mkdir($local_dir ,0777 ,true);
        }
        //存入本地地址;
        $local_dir_file = $local_dir.$order_id.'.pdf';
        file_put_contents($local_dir_file, file_get_contents($doc_url));

        //上传阿里云地址;
        $shop_name= "Woobilly";
        $shop_name= str_replace(' ', '', $shop_name);
        $ossDir   = 'package/' .date('ymd').'/'.$shop_name.'/'.$order_id.'.pdf';
        $res      = $service->uploads($local_dir_file,$ossDir);
        //上传后清除本地数据
        unlink($local_dir_file);
        return $this->jsonMessage(200, true, '上传成功', $res);
    }



    /**
     * @desc 本地数据上传OSS
     * @author luckyXiong
     * @Date   2024/03/18 10:55
     */
    public function uploadImage($params=[]){
        $doc_url   = $params['url']??'';
        //地址上传到阿里云OSS;
        $service   = new UploadService();
        $BASE_PATH = dirname(__DIR__, 1);
        $local_dir = $BASE_PATH . '/runtime/images/';
        $unique_key = uniqid();
        if (!is_dir($local_dir)) {
            mkdir($local_dir ,0777 ,true);
        }
        //存入本地地址;
        $local_dir_file = $local_dir.$unique_key.'.png';
        file_put_contents($local_dir_file, file_get_contents($doc_url));

        //上传阿里云地址;
        $ossDir   = 'images/' .date('ymd').'/'.$unique_key.'.png';
        $res      = $service->uploads($local_dir_file,$ossDir);
        //上传后清除本地数据
        unlink($local_dir_file);
        return $res['info']['url']??'';
    }


    /**
     * @desc 本地数据上传OSS
     * @author luckyXiong
     * @Date   2024/03/18 10:55
     */
    public function uploadSkuImage($params=[]){
        $doc_url   = $params['url']??'';
        //地址上传到阿里云OSS;
        $service   = new UploadService();
        $BASE_PATH = dirname(__DIR__, 1);
        $local_dir = $BASE_PATH . '/runtime/skuImages/';
        $unique_key = time();
        if (!is_dir($local_dir)) {
            mkdir($local_dir ,0777 ,true);
        }
        //存入本地地址;
        $local_dir_file = $local_dir.$unique_key.'.png';
        file_put_contents($local_dir_file, file_get_contents($doc_url));

        //上传阿里云地址;
        $ossDir   = 'skuImages/' .date('ymd').'/'.$unique_key.'.png';
        $res      = $service->uploads($local_dir_file,$ossDir);
        //上传后清除本地数据
        unlink($local_dir_file);
        return $res['info']['url']??'';
    }





    /**
     * @desc  本地excel数据上传异步操作
     * @author luckyXiong
     * @Date   2024/03/20 10:55
     */
    public function uploadExcelTest($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_INCOMPLETE_SKU,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }



    /**
     * @desc  本地excel数据上传异步操作
     * @author luckyXiong
     * @Date   2024/06/04 10:55
     */
    public function uploadTimeExcelTest($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_INCOMPLETE_TIME,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }








    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return  [
            'order_id'         => empty($row['A'])? '': trim($row['A']),
            'shop_id'          => empty($row['B'])? '': trim($row['B']),
            'package_id'       => empty($row['C'])? '': trim($row['C']),
        ];
    }

    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_detail($params=[]){
        $key = 'amazon_incomplete_sku:'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 500);
        $order_id    = getIsset($params,'order_id');
        $shop_id     = getIsset($params,'shop_id');
        $package_id  = getIsset($params,'package_id');

        //数据入库逻辑
        $info = [
            'order_id'       =>$order_id,
            'shop_id'        =>$shop_id,
            'package_id'     =>$package_id,
            'created_time'   =>date("Y-m-d H:i:s", time()),
        ];

        $res = Db::name('test_orderinfo')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }

    //测试 getIMConversations
    public function getWhOrder($param=[]){

    }







    /**
     * @desc    会话中的sku信息组装
     * @author  xx
     * @date    2024-05-29
     */
    public function get_sku_info($params=[]){
        $order_id       = $params['order_id']??'';
        if(!$order_id)   return ['msg'=>'订单ID不能为空!'];
        $order_append   = Db::name('order_append')->where('order_id',$order_id)->field('json')->find();
        $info           = json_decode($order_append['json'],true);
        $order_info     = Db::name('order')->where('order_id',$order_id)->field('createtime,shop_id')->find();
        $order_info_arr = $insert_info = [];
        foreach($info['line_items'] as $line_item){
            $sku_image  = self::uploadSkuImage(['url'=>$line_item['sku_image']]);
            $order_info_arr[] = [
                'order_id'        => $info['id']??'',
                'shop_id'         => $order_info['shop_id']??'',
                'info_id'         => $line_item['id']??'',
                'product_id'      => $line_item['product_id']??'',
                'product_name'    => $line_item['product_name']??'',
                'seller_sku'      => $line_item['seller_sku']??'',
                'sku_name'        => $line_item['sku_name']??'',
                'sku_image'       => $sku_image,
                'sale_price'      => $line_item['sale_price']??'',
                'createtime'      => $order_info['createtime']??'',
            ];
        }

        foreach($order_info_arr as $v){
             $exist = Db::name('im_order_info')->where(['order_id'=>$v['order_id'],'info_id'=>$v['info_id']])->value('id');
             if($exist) continue;
            $insert_info[] = $v;
        }
        if($insert_info){
            Db::name('im_order_info')->insertAll($insert_info);
        }
        return  true;
    }



    /**
     * @desc   获取会话消息列表
     * @author xx
     * @date 2024-05-17
     */
    public function get_conversations_mess($params=[]){
       $shop_id         = $params['shop_id']??'';
       $conversation_id = $params['conversation_id']??'';
       $order_id        = $params['order_id']??'';
       $next_page_token = '';
        do {
            $return_list     = self::gets_message($shop_id, $conversation_id, $next_page_token);
            $messages_info   = $return_list['messages_info'];
            $next_page_token = $return_list['next_page_token'];
            self::insert_message($messages_info, $shop_id, $conversation_id, $order_id);
            if(empty($next_page_token)) {
                break;
            }
        }while(true);

    }

    /**
     * @desc   获取会话下所有消息
     * @author xx
     * @date   2024-05-21
     */
    public function gets_message($shop_id,$conversation_id,$page_token){
        $account         = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $path            = Config('Logisticskey.TIKTOK.create_conversations_path').'/'.$conversation_id.'/messages';
        $base_url        = Config('Logisticskey.TIKTOK.basic_url');
        if($page_token){
            $sign = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'page_size' . '10' . 'page_token' . $page_token . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '' . $account['app_secret'];
        }else{
            $sign = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key']. 'page_size' . '10'.'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '' . $account['app_secret'];
        }
        $sign     = hash_hmac('sha256', $sign, $account['app_secret']);
        if($page_token){
            $url             = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time(). '&page_size=' . '10'. '&page_token=' . $page_token;
        }else{
            $url             = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time(). '&page_size=' . '10';
        }
        $return          = HttpUtil::tikGetUrl($url, $account['access_token']);
        $messages_info   = $return['data']['messages']??[];
        $next_page_token = $return['data']['next_page_token']??'';
        return  ['messages_info'=>$messages_info,'next_page_token'=>$next_page_token];
   }


    /**
     * @desc   写入数据
     * @author xx
     * @date   2024-05-21
     */
   public function insert_message($messages_info,$shop_id,$conversation_id,$order_id){
       if(!$messages_info)  return ['msg'=>'数据为空!'];
       //获取店铺头像;
       $shop_avatar     = Db::name('im_shop_template')->where('shop_id',$shop_id)->value('customer_avatar');
       $messages_arr    = $insert_arr = $buyer_arr = [];
       foreach($messages_info as $k=>$v){
           $is_visible         = $v['is_visible'];
           $type               = $v['type']??'';
           $send_info          = $v['sender']??[];
           $send_avatar        = $send_info['avatar']??'';
           $send_im_user_id    = $send_info['im_user_id']??'';
           $send_nickname      = $send_info['nickname']??'';
           $send_role          = $send_info['role']??'';
           if(false==$is_visible || $type!='TEXT') continue;

           $content            = json_decode($v['content'],true);

           if($send_role == 'BUYER'){
               $avatar = self::uploadImage(['url'=>$send_avatar]);
           }else{
               $avatar = $shop_avatar;
           }

           $messages_arr[$k]['shop_id']         = $shop_id;
           $messages_arr[$k]['conversation_id'] = $conversation_id;
           $messages_arr[$k]['order_id']        = $order_id;
           $messages_arr[$k]['content']         = $content['content']??'';
           $messages_arr[$k]['message_id']      = $v['id'];
           $messages_arr[$k]['conversations_message_id'] = md5($conversation_id.$v['id']);
           $messages_arr[$k]['message_nickname'] = $send_nickname;
           $messages_arr[$k]['message_avatar'] = $avatar;
           $messages_arr[$k]['message_role']  = $send_role;
           $messages_arr[$k]['message_im_id'] = $send_im_user_id;
           $messages_arr[$k]['message_type']  = 1;
           $messages_arr[$k]['timestamp']     = $v['create_time'];
           $messages_arr[$k]['created_time']  = date("Y-m-d H:i:s", $v['create_time']);
       }
       if(!$messages_arr)  return  '暂无数据!';

       foreach($messages_arr as $v){
           $exist_message = Db::name('im_conversations_message')->where('conversations_message_id',$v['conversations_message_id'])->field('id')->find();
           if($exist_message) continue;
           $insert_arr[]  = $v;
       }

       if($insert_arr){
           Db::name('im_conversations_message')->insertAll($insert_arr);
           foreach($insert_arr as $v){
               if($v['message_role']=='BUYER'){
                   $buyer_arr[] = $v;
               }
           }

           //有用户的消息;
           if($buyer_arr){
               self::get_current_buyer($buyer_arr,$conversation_id);
           }
       }
   }


    /**
     * @desc   获取主表的最新的用户回复信息
     * @author xx
     * @date   2024-05-29
     */
    private function get_current_buyer($buyer_arr,$conversation_id){
        $sort = array_column($buyer_arr,'timestamp');
        array_multisort($sort,SORT_DESC,$buyer_arr);
        $first_arr = current($buyer_arr);
        //更新会话主表
        $update_arr = [
            'message_content'        =>$first_arr['content']??'',
            'message_time'           =>$first_arr['timestamp']??'',
            'message_id'             =>$first_arr['message_id']??'',
            'im_status'              =>1,
            'created_time'           =>date("Y-m-d H:i:s", $first_arr['timestamp']),
        ];
        Db::name('im_conversations')->where('conversation_id',$conversation_id)->update($update_arr);
    }






    /**
     * @desc   消息标记为已读
     * @author xx
     * @date   2024-05-19
     */
    public function messages_read_operate($params=[]){
        $conversation_id = $params['conversation_id']??'';
        $shop_id         = $params['shop_id']??'';
        $account         = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $path            = Config('Logisticskey.TIKTOK.create_conversations_path').'/'.$conversation_id.'/messages/read';
        $base_url        = Config('Logisticskey.TIKTOK.basic_url');
        $sign            = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"conversation_id":"' . $conversation_id . '"}' . $account['app_secret'];
        $sign            = hash_hmac('sha256', $sign, $account['app_secret']);
        $url             = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        return HttpUtil::tikPostUrl($url, ['conversation_id'=>$conversation_id], $account['access_token']);
    }




    /**
     * @desc   批量发送消息数据准备
     * @author xx
     * @date   2024-05-21
     */
    public function get_batch_send_order(){
        $where      = [];
        $start_time = strtotime(date('Y-m-d 00:00:00', time()-timezone()-24*3600));
        $end_time   = strtotime(date('Y-m-d 23:59:59', time()-timezone()-24*3600));
        $where[]    = ['o.createtime', '>=', $start_time];
        $where[]    = ['o.createtime', '<=', $end_time];
        $where[]    = ['o.status', 'not in', ['CANCELLED,ON_HOLD,UNPAID']];

        $field      = ['o.id,o.order_id,o.shop_id,o.createtime,append.user_id as buyer_user_id'];
        $list       = Db::name('order')
            ->alias('o')
            ->leftJoin('ba_order_append append', 'o.order_id = append.order_id')
            ->field($field)
            ->where($where)
            ->select();
        $list       = objectToArray($list);
        $insert_arr = [];
        //批量获取店铺IM信息;
        $shop_ids   = array_column($list,'shop_id');
        $shop_ids   = array_values(array_unique($shop_ids));
        $shop_ims   = Db::name('im_shop_template')->whereIn('shop_id',$shop_ids)
                     ->field('shop_id,customer_nickname,customer_avatar,customer_role,customer_im_id')
                     ->select()->toArray();
        $shop_ims_map = array_column($shop_ims,null,'shop_id');
        foreach($list as $v){
            if(!$v['buyer_user_id']) continue;
            // 检查订单ID是否重复
            $existingOrder = Db::name('im_batch_conversations')
                ->where('order_id', $v['order_id'])
                ->value('order_id');

            if ($existingOrder)   continue;
                $shop_ims_info = $shop_ims_map[$v['shop_id']]??[];
                $insert_arr[] = [
                      'shop_id'          =>$v['shop_id'],
                      'order_id'         =>$v['order_id'],
                      'buyer_user_id'    =>$v['buyer_user_id'],
                      'customer_nickname'=>$shop_ims_info['customer_nickname']??'',
                      'customer_avatar'  =>$shop_ims_info['customer_avatar']??'',
                      'customer_role'    =>$shop_ims_info['customer_role']??'',
                      'customer_im_id'   =>$shop_ims_info['customer_im_id']??'',
                      'createtime'       =>$v['createtime']??'',
                      'created_time'     =>date("Y-m-d H:i:s", time()),
                ];
        }

        //数据批量写入库中;
        if($insert_arr){
            Db::name('im_batch_conversations')->insertAll($insert_arr);
        }
    }





    /**
     * @desc   更新订单状态MQ消费方法
     * @author xx
     * @date   2024-06-06
     */
    public function update_status_consumer($info=[]){
        $orderId = $info['order_id']??'';
        $shopId  = $info['shop_id']??'';
        $shop    = Db::name('shops')->where('id',$shopId)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $tik_info = Config::get('Logisticskey.' . 'TIKTOK');
        $baseUrl  = $tik_info['basic_url'];
        $path     = $tik_info['orders_info_path'];
        $sign     = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'ids' . $orderId . 'shop_cipher' . $shop['cipher'] . 'timestamp' . time() . '' . $shop['app_secret'];
        $sign     = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url      = $baseUrl . $path . "?app_key=" . $shop['app_key'] . "&shop_cipher=" . $shop['cipher'] . "&sign=" . $sign . "&timestamp=" . time() . '&ids=' . $orderId;
        $return   = HttpUtil::tikGetUrl($url, $shop['access_token']);
        if (!isset($return['data']['orders'][0]) || empty($return['data']['orders'][0]))  return [201, false, '暂无数据!'];
        $orderinfo  = $return['data']['orders'][0];
        $platform_discount = $orderinfo['payment']['platform_discount']??'';
        if($orderinfo['status']=='CANCELLED'){
             $cancel_time = $orderinfo['cancel_time']??0;
        }else{
            $cancel_time  = 0;
        }
        Db::name('order')->where('order_id',$orderId)->update(
            [
                'status'             => $orderinfo['status'],
                'platform_discount'  => $platform_discount,
                'cancel_time'        => $cancel_time,
            ]
        );
        return  true;
    }



}